package cn.topartip.filters;

import com.alibaba.nacos.api.config.annotation.NacosValue;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.List;

@Configuration
public class WhiteCheckerFilter02 implements GlobalFilter, Ordered {
    @NacosValue(value = "${whiteList}",autoRefreshed = true)
    private List<String> whiteListPatterns;
    @NacosValue(value = "${auth.typeKey}",autoRefreshed = true)
    String authTypeKey;

    private static final PathMatcher pathMatcher = new AntPathMatcher();
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        RequestPath path = exchange.getRequest().getPath();
        ServerHttpRequest.Builder mutate = exchange.getRequest().mutate();
        // 检查路径是否在白名单中
        if (isWhiteListed(path.value())) {
            // 如果是，则允许请求继续
            mutate.header(authTypeKey,"whiteList");
        }else{
            mutate.header(authTypeKey,"needAuth");
        }
        return chain.filter(exchange);
    }

    private boolean isWhiteListed(String path) {
        // 这里使用AntPathMatcher或类似的工具来匹配路径
        for (String pattern : whiteListPatterns) {
            if (pathMatcher.match(pattern, path)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE+101;
    }
}
